package vip.xiaonuo.biz.modular.pay.util.bankpay;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.ser.ToXmlGenerator;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.InputSource;
import vip.xiaonuo.biz.modular.pay.param.resp.BizPayOrderResp;
import vip.xiaonuo.common.exception.CommonException;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


/**
 * 实体类转xml报文格式
 *
* @Author:薛守立
* @CreateTime:2024/9/5 11:26
 *
*/

public class XmlUtils {

    private static final Logger logger = LoggerFactory.getLogger(XmlUtils.class);


    private static final String XML_HEAD = "<?xml version=\"1.0\" encoding=\"UTF_8\" ?>\n";

    public static String javaBeanToXml(Object object){
        String xml = "";
        if(Objects.isNull(object)) return xml;
        try {
            XmlMapper xmlMapper = new XmlMapper();
            xml = xmlMapper.writeValueAsString(object);
            logger.info("转化结果：{}",xml);
        }catch (Exception ignored){
            throw new CommonException("请求对象解析 xml 格式化错误");
        }
        return XML_HEAD + xml;
    }

    public static BizPayOrderResp xmlToJavaBean(String xml)  {
        try {
            XmlMapper xmlMapper = new XmlMapper();
            xmlMapper.configure(ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true);
            // 将xml转化为对象
            return xmlMapper.readValue(xml, BizPayOrderResp.class);
        }catch (JsonProcessingException e){
            throw new CommonException("支付接口格式解析错误");
        }

    }


    /**
     * 重构map转化方法
     */
    public static Map toMap(String body ) throws Exception{
        ObjectMapper mapper = new ObjectMapper();
        return mapper.readValue(body, Map.class);
    }

    /**
     * 转XMLmap
     * @author
     * @param xmlBytes
     * @param charset
     * @return
     * @throws Exception
     */
    public static Map<String, String> toMap(byte[] xmlBytes, String charset) throws Exception{
        SAXReader reader = new SAXReader(false);
        InputSource source = new InputSource(new ByteArrayInputStream(xmlBytes));
        source.setEncoding(charset);
        Document doc = reader.read(source);
        Map<String, String> params = XmlUtils.toMap(doc.getRootElement());
        return params;
    }

    /**
     * 转MAP
     * @author
     * @param element
     * @return
     */
    public static Map<String, String> toMap(Element element){
        Map<String, String> rest = new HashMap<String, String>();
        List<Element> els = element.elements();
        for(Element el : els){
            rest.put(el.getName().toLowerCase(), el.getText());
        }
        return rest;
    }
}
